<template>
  <div class="page-main" v-title data-title="公司信息">
    <a-spin :spinning="btnLoading">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container" ref="imageWrapper">
      <div class="head-content">
        <span class="bold-font">{{titleDesc}}</span>
        <!-- <div class="btn-line">
          <a-button class="hte-btn add-btn" type="primary">提交</a-button>
        </div> -->
      </div>
      <div class="floatNav"  >
        <a-button
          v-if="submitlBtn"
          type="primary"
          @click="handleSubmit"
          :loading="btnLoading"
          >提交审批</a-button>
        <a-button v-if="deleteBtn || (submitlBtn && !this.hasChange)"  type="default"
           class=" delete-btn" @click="handleDeleteCompany">删除公司</a-button>
        <a-button v-if=" (submitlBtn && hasChange && !!changeId)"  type="default"
           class=" delete-btn" @click="handleDeleteChangeCompany">删除变更</a-button>
        <a-button
          v-if="!!companyId && computedStatus >2"
          
          @click="handleClick('det', companyId)"
          >公司明细</a-button>
      </div>
       <div style="width: 150px">
    
        <a-tag style="position: fixed; top: 180px; right: 20px;z-index:2" :color="statusColor" >
          {{statusText}}
        </a-tag>
       
      </div>
      <div class="content">
      <j-form-container :disabled="changeDisable">
        <a-form-model
          class="hte-form-model"
          ref="ruleForm"
          :model="form"
          :rules="rules"
          slot="detail"
        >
          <section>
            <div class="section-header">基本信息</div>
            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item
                  class="file-upload-model"
                  label="-"
                >
                  <template>
                    <ht-upload
                      ref="myUpload"
                      class="upload-demo"
                      :multiple="false"
                      dbKey="Trd"
                      busField="libraryCompany"
                      busType="libraryCompany"
                      ftpKey="ftp"
                      v-model="fileList"
                      busKey="libraryCompany"
                      :show-file-list="false"
                      :before-upload="(value) => beforUpload(value, '企业证照')"
                      :on-success="(value) => fileUploadSuccess(value, 'enterpriseLicense')"
                    >
                      <div class="file-upload-add" v-if="!enterpriseLicenseUrl">
                        <template>
                          <a-icon type="plus" />
                          <p>企业证照</p>
                        </template>
                      </div>
                      <div class="file-upload-png" v-else>
                        <img :src="enterpriseLicenseUrl" alt="企业证照" />
                        <span title="查看大图" @click="handleImage($event, 'det', 'enterpriseLicense')"
                          ><a-icon type="eye"
                        /></span>
                        <span title="删除" @click="handleImage($event, 'del', 'enterpriseLicense')"
                          ><a-icon type="delete"
                        /></span>
                        <span title="重新上传"><a-icon type="swap" /></span>
                      </div>
                    </ht-upload>
                    <span class="upload-tip">企业证照只能上传png/jpeg/jpg图片文件，且图片大小不能超过2M</span>
                  </template>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="公司名称" prop="name">
                  <a-input v-model.trim="form.name" placeholder="请输入公司名称" :maxLength="100"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="企业状态" prop="status">
                  <a-select
                    v-model="form.status"
                    placeholder="请选择企业状态"
                    @change="(value) => handleChange(value, 'status')"
                  >
                    <a-select-option v-for="item in dics.status" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!-- 传中文，不传code 公司规模\行业分类-->
                <a-form-model-item label="公司规模" prop="size">
                  <a-select
                    v-model="form.size"
                    placeholder="请选择公司规模"
                    @change="(value) => handleChange(value, 'size', 'sizeType')"
                  >
                    <a-select-option v-for="(item, key) in dics.sizeType" :key="key" :value="item.name">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="统一社会信用代码" prop="code">
                  <a-input v-model.trim="form.code" placeholder="请输入统一社会信用代码" :maxLength="18" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="注册号">
                  <a-input v-model.trim="form.registrationNumber" placeholder="请输入注册号" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item class="col-input-2" label="注册资本" prop="registeredCapital">
                  <a-input-number
                    v-model="form.registeredCapital"
                    :precision="2"
                    :min="0"
                    placeholder="请输入注册资本"
                  />
                  <a-select
                    v-model="form.registeredCapitalUnit"
                    @change="(value) => handleChange(value, 'registeredCapitalUnit')"
                    placeholder="请选择注册资本单位"
                  >
                    <a-select-option v-for="item in dics.registeredCapitalUnit" :key="item.code" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="法定代表人" prop="legal">
                  <a-input v-model.trim="form.legal" placeholder="请输入法定代表人" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="公司类型" prop="type">
                  <a-select
                    v-model="form.type"
                    @change="(value) => handleChange(value, 'type', 'companyType')"
                    placeholder="请选择公司类型"
                  >
                    <a-select-option v-for="(item, key) in dics.companyType" :key="key" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <!-- 传中文，不传code 公司规模\行业分类 -->
                <a-form-model-item label="行业分类" prop="industry">
                  <a-select
                    v-model="form.industryName"
                    @change="(value) => handleChange(value, 'industry','industry')"
                    placeholder="请选择行业分类"
                  >
                    <a-select-option v-for="(item, key) in dics.industry" :key="key" :value="item.name">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  
                </a-form-model-item>
                <!-- 传中文，不传code 公司规模\行业分类 -->
                <!-- <a-form-model-item label="行业分类" prop="industryName">
                  <a-select
                    v-model="form.industryName"
                    @change="(value) => handleChange(value, 'industryName', '')"
                    placeholder="请选择行业分类"
                  >
                    <a-select-option v-for="(item, key) in dics.industryName" :key="key" :value="item.industryName">
                      {{ item.industryName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item> -->
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="成立日期" prop="establishTime">
                  <a-date-picker
                    v-model="form.establishTime"
                    :valueFormat="dateFormat"
                    style="width: 100%"
                    placeholder="请选择成立日期"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="核准日期" prop="approvalTime">
                  <a-date-picker
                    v-model="form.approvalTime"
                    :valueFormat="dateFormat"
                    style="width: 100%"
                    placeholder="请选择核准日期"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否长期营业">
                  <a-radio-group v-model="form.businessTermLong" @change="onChangeRadio" style="width: 100%">
                    <a-radio value="是">是</a-radio>
                    <a-radio value="否">否</a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>              
            </a-row>
            <a-row :gutter="24">              
              <a-col :span="8">
                <a-form-model-item  class="col-input-2" label="公司分类" prop="companyClass">                  
                  <a-select
                    v-model="form.companyClass"
                    :dropdownMatchSelectWidth="false"
                    @change="(value) => handleChange(value, 'companyClass')"
                    placeholder="请选择公司分类首页"
                  >
                    <a-select-option v-for="(item, key) in dics.companyClass" :key="key" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <a-select
                    v-model="form.companyClassDetails"
                    :dropdownMatchSelectWidth="false"
                    @change="(value) => handleChange(value, 'companyClassDetails')"
                    placeholder="请选择公司分类明细"
                  >
                    <a-select-option v-for="(item, key) in dics.companyClassDetails" :key="key" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>           
              <a-col :span="8">
                <a-form-model-item label="营业期限" prop="businessTerm">
                  <a-date-picker
                    v-model="form.businessTerm"
                    :valueFormat="dateFormat"
                    style="width: 100%"
                    placeholder="请选择营业期限"
                    :disabled = "form.businessTermLong == '是'"
                  />
                </a-form-model-item>
              </a-col>
               <!-- <a-col :span="8">
                <a-form-model-item label="公司性质" prop="natureOfCompany">
                  <a-select
                    v-model="form.natureOfCompany"
                    @change="(value) => handleChange(value, 'natureOfCompany')"
                    placeholder="请选择公司性质"
                  >
                    <a-select-option v-for="(item, key) in dics.natureOfCompany" :key="key" :value="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col> -->
              <!-- <a-col :span="8">
                <a-form-model-item label="住所" class="lable-red">
                  <area-select ref="areaRef"  :changeOnSelect="true" placeholder="请选择地区" @changeArea="changeArea"></area-select>
                </a-form-model-item>
              </a-col> -->
              <a-col :span="4">
                <a-form-model-item label="公司代码"  >
                  
                   <!-- <a-select
                    v-model="form.companyCode"
                    :dropdownMatchSelectWidth="false"
                    @change="(value) => handleChange(value, 'companyCode')"
                    placeholder="请选择公司代码"
                  >
                    <a-select-option v-for="(item, key) in dics.companyCode" :key="key" :value="item.code">
                      {{ item.code }}
                    </a-select-option>
                  </a-select> -->
                  <a-input :disabled="true"  v-model.trim="form.companyCode" placeholder="自动更新" :maxLength="25"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="4">
                <a-form-model-item label="销售组织"  >
                  
                  <a-input :disabled="true" v-model.trim="form.companySalesOrganization" placeholder="自动更新" :maxLength="25"/>
                </a-form-model-item>
              </a-col>
            </a-row>
             <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="住所" class="lable-red">
                  <area-select v-if="!areaLableShow" ref="areaRef"  :changeOnSelect="true" placeholder="请选择地区" @changeArea="changeArea"></area-select>
                  <span v-else>{{form.addressAreaLabel}}</span>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item
                  label="详细地址"
                  prop="addressDetails"
                >
                  <a-input v-model.trim="form.addressDetails" placeholder="请输入详细地址"/>
                </a-form-model-item>
              </a-col>

               <a-col :span="8">
                 <!-- 传中文，不传code 企业资质 -->
                 <a-form-model-item label="企业资质（可多选）" prop="qualification">
                   <a-select
                     v-model="form.qualification"
                     mode = "multiple"
                     placeholder="请选择企业资质"
                     @change="handleMultipleChange"
                     >
                     <a-select-option v-for="(item, key) in dics.qualification" :key="key" :value="item.code">
                       {{ item.name }}
                     </a-select-option>
                   </a-select>
                 </a-form-model-item>
               </a-col>

            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item
                  label="经营范围"
                  prop="businessScope"
                >
                  <a-textarea
                    v-model.trim="form.businessScope"
                    :auto-size="{ minRows: 3, maxRows: 15 }"
                    style="width: 100%"
                    placeholder="请输入经营范围"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="政策管理员"  >
                  <a-select
                      show-search
                      allow-clear
                      v-model="form.policyAdmin"
                      placeholder="输入账号或者名称查找用户"
                      style="width: 100%"
                      :filter-option="false"
                      :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                       @search="(val)=>fetchUser(val,null,'userDataPolicy')"
                      @change="(value, option)=>handleDictChange(value, 'userDataPolicy', 'policyAdminName',1)"
                     
                    >
                      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                      <a-select-option v-for="(d, index) in userDataPolicy" :key="index" :value="d.username">
                        {{ d.realname }}
                      </a-select-option>
                    </a-select>

                </a-form-model-item>
              </a-col>
               <a-col :span="8">
                <a-form-model-item label="政策管理主管"  >
                  
                  <a-select
                      allow-clear
                      show-search
                      mode="multiple"
                      v-model="form.policyCharge"
                      placeholder="输入账号或者名称查找用户，可多选"
                      style="width: 100%"
                      :filter-option="false"
                      :not-found-content="fetching ? '找不到记录' : '找不到记录'"
                      @search="(val)=>fetchUser(val,null,'userData')"
                      @change="(value, option)=>handleDictChange(value, option, 'policyChargeName')"
                    >
                      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
                      <a-select-option v-for="(d, index) in userData" :key="index" :value="d.username">
                        {{ d.realname }}
                      </a-select-option>
                    </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section v-if="false">
            <div class="section-header">企业人员</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="企业总人数">
                  <a-input v-model="companySizeInfo.totalNumber" placeholder="请输入企业总人数" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="研发总人数">
                  <a-input v-model="companySizeInfo.developmentNumber" placeholder="请输入研发总人数" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="研发人员占比">
                  <a-input v-model="companySizeInfo.developmentRatio" placeholder="请输入研发人员占比" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="博士学位人数">
                  <a-input v-model="companySizeInfo.doctorNumber" placeholder="请输入博士学位人数" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="硕士学位人数">
                  <a-input v-model="companySizeInfo.masterNumber" placeholder="请输入硕士学位人数" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="本科学历人数">
                  <a-input v-model="companySizeInfo.undergraduateNumber" placeholder="请输入本科学历人数" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="大专及以上人数">
                  <a-input v-model="companySizeInfo.juniorCollegeAboveNumber" placeholder="请输入大专及以上人数" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <!-- 变更信息 -->
          <ProjectInfoChange  ref="projectInfoChange" v-if="showChange" :projectBuildId="companyChangeDetail.projectBuildId" :companyId="companyChangeDetail.companyId" :projectNo="companyChangeDetail.projectNo"></ProjectInfoChange>
          <section v-if="isNewCompany==0">
            <div class="section-header">知识产权</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="国内专利总数">
                  <a-input-number
                    v-model="companySizeInfo.totalDomesticPatents"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入国内专利总数"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="国内发明专利">
                  <a-input-number
                    v-model="companySizeInfo.domesticInventionPatent"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入国内发明专利"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="国内实用新型">
                  <a-input-number
                    v-model="companySizeInfo.domesticUtilityModel"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入国内实用新型"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8" v-if="false">
                <a-form-model-item label="知识产权总数">
                  <a-input-number
                    v-model="companySizeInfo.totalIntellectualProperty"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入知识产权总数"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="软件著作权">
                  <a-input-number
                    v-model="companySizeInfo.softwareCopyright"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入软件著作权"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="PCT专利">
                  <a-input-number
                    v-model="companySizeInfo.pclNumber"
                    :precision="0.1"
                    :min="0"
                    placeholder="请输入PCT专利"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section>
            <div class="section-header">
              股东信息
              <a-button class="hte-btn add-btn" type="primary" @click="handleAdd('sourceData')">新增</a-button>
            </div>
            <div class="section-table">
              <a-table
                class="hte-table-content"
                :columns="payColumns"
                :data-source="sourceData"
                :pagination="false"
                :loading="tabLoading"
                bordered
                size="middle"
              >
                <template slot="num" slot-scope="text, record, index">
                  {{ parseInt(index) + 1 }}
                </template>
                <template slot="name" slot-scope="text, record,index">
                  <a-input v-model="record.name" @change="handleHolding('change',record,index,'sourceData')"/>
                </template>
                <template slot="proportion" slot-scope="text, record">
                  <a-input-number v-model="record.proportion" :min="0" :precision="2" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')"/>
                </template>
                <template slot="operation" slot-scope="text, record, index">
                  <a @click="handleDelete(record, 'sourceData', index)">删除</a>
                   <a-divider  type="vertical" />
                  <a @click="handleHolding('det',record)">查看</a>
                </template>
              </a-table>              
            </div>
          </section>
          <section>
            <div class="section-header">
              <span>股权穿透图
                <span class="upload-tip">只能上传png/jpeg/jpg图片文件，且图片大小不能超过2M</span>
              </span>
              <a-button v-if="stockRightImageUrl" class="hte-btn add-btn" type="primary" @click="handleImage($event, 'det', 'stockRightImage')">查看大图</a-button>
            </div>
            <div class="section-table">
              <template>
                <ht-upload
                  ref="myUpload"
                  class="upload-demo upload-stock"
                  :multiple="false"
                  dbKey="Trd"
                  busField="stockRightImage"
                  busType="stockRightImage"
                  ftpKey="ftp"
                  v-model="stockRightFile"
                  busKey="stockRightImage"
                  :show-file-list="false"
                  :before-upload="(value) => beforUpload(value, '股权穿透图')"
                  :on-success="(value) => fileUploadSuccess(value, 'stockRightImage')"
                >
                  <div class="file-upload-add file-upload-stockadd" v-if="!stockRightImageUrl">
                    <template>
                      <a-icon type="plus" title="股权穿透图"/>
                    </template>
                  </div>
                  <div class="file-upload-png file-upload-stock" v-else>
                    <img :src="stockRightImageUrl" alt="股权穿透图" />
                    <span title="查看大图" @click="handleImage($event, 'det', 'stockRightImage')"
                      ><a-icon type="eye"
                    /></span>
                    <span title="删除" @click="handleImage($event, 'del', 'stockRightImage')"
                      ><a-icon type="delete"
                    /></span>
                    <span title="重新上传"><a-icon type="swap" /></span>
                  </div>
                </ht-upload>                
              </template>
            </div>
          </section>
          <section>
            <div class="section-header">主要人员信息</div>
            <div class="section-content">
              <div v-for="(item, index) of personnelList" :key="index" class="info-box" @click="handlePersonnel(index)">
                <p :title="item.userName">{{ item.userName || '-' }}</p>
                <p :title="item.typeName">{{ item.typeName || '-' }}</p>
                <span><a-icon type="edit" /></span>
              </div>
              <!-- <div class="info-box"><a-icon type="plus" /></div> -->
            </div>
          </section>
          <section v-if="!cpuNewCompany">
            <div class="section-header">
              企业参股控股公司
              <a-button class="hte-btn add-btn" type="primary" @click="handleAdd('holdingData')">新增</a-button>
            </div>
            <div class="section-table">
              <a-table
                class="hte-table-content"
                :columns="holdingColumns"
                :data-source="holdingData"
                :loading="holdLoading"
                bordered
                size="middle"
                :pagination="false"
              >
                <template slot="num" slot-scope="text, record, index">
                  {{ parseInt(index) + 1 }}
                </template>
                <template slot="companyName" slot-scope="text, record,index">
                  <a-input v-model="record.companyName" @change="handleHolding('change',record,index,'holdingData')"/>
                </template>
                <template slot="companyCode" slot-scope="text, record">
                  <a-input v-model="record.companyCode" />
                </template>
                <template slot="proportion" slot-scope="text, record">
                  <a-input-number v-model="record.proportion" :min="0" :precision="2" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')"/>
                </template>
                <template slot="operation" slot-scope="text, record, index">
                  <a @click="handleDelete(record, 'holdingData', index)">删除</a>
                    <a-divider  type="vertical" />
                  <a @click="handleHolding('det',record)">查看</a>
                </template>
              </a-table>
            </div>
          </section>
         
        </a-form-model>
        </j-form-container>
         <section v-if="!!processInstanceId">
            <div class="section-header">流程信息</div>
            <template>
              <ApprovalInfo ref="approvalInfo"></ApprovalInfo>
            </template>
          </section>
      </div>
    </div>
    <div class="btn-box">
      <!-- <a-button class="hte-btn add-btn">取消</a-button> -->
       
      <a-button v-if="saveBtnHasPermission"  class="hte-btn add-btn" :loading="btnLoading" type="" @click="handleSaveBtnHasPermission">发起变更</a-button>
      <a-button v-if="saveBtn"  class="hte-btn add-btn" :loading="btnLoading" type="" @click="handleSaveCreat">保存</a-button>
      <a-button v-if="approvelBtn" v-has="'company:approval'"  class="hte-btn add-btn" :loading="btnLoading" type="" @click="handleSaveApprove">保存</a-button>
      <a-button v-if="approvelBtn && !processInstanceId" v-has="'company:approval'" class="hte-btn add-btn" :loading="btnLoading" type="primary" @click="handleApprove">同意提交</a-button>
      
    </div>
    <!-- 弹框模板 -->
    <a-modal v-model="visibleModel" title="人员信息" @ok="handleClassOk" @cancel="handleCancel">
      <a-form-model
        class="hte-form-model visible-model"
        ref="ruleModelForm"
        :model="visibleForm"
        :rules="visibleRules"
      >
        <a-row :gutter="24" style="margin-bottom: 10px">
          <a-col :span="24">
            <a-form-model-item label="成员名称:" prop="userName">
              <a-input v-model.trim="visibleForm.userName" :maxLength="100"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="成员类型:">
              <a-input v-model="visibleForm.typeName" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
     <a-back-top  style="right:50px;"/>
     <HteLibCompanySendMessage ref="companyMessag" @ok="finishNoticeUserSubmit"></HteLibCompanySendMessage>
       <process-user-select
      :columns="submitUserCols"
      :winHeight="150"
      :winWidth="550"
      @selectUserConfirm="selectUserConfirm"
      ref="processUserSelect"
    />
     </a-spin>
  </div>
</template>
<script>
import { getAction, postAction ,deleteAction} from '@/api/manage'
import '@/config/upload.install.js'
import { companyMixin } from '@/views/library/company/companyMixin'
import {filterHasPermission} from '@/utils/hasPermission'
import cloneDeep from 'lodash/cloneDeep'
import {codeInfoList,codeInfoByTypeAndParent} from '@/api/codeInfo'
import {Modal} from 'ant-design-vue'
import Vue from 'vue'
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
Vue.use(Viewer, {
    defaultOptions: {zIndex: 9999,}
})
const saveFlag = {a:false,b:false,c:false,d:false,e:false}
const saveFlagTue = {a:true,b:true,c:true,d:true,e:true}
const statusCreatText = {'1':'创建中','2':'审批中','3':'已入库'}
const statusChangeText = {'1':'变更中','2':'审批中','3':'已入库'}
const statusColor={'1':'red','2':'orange', '3':'green' }
export default {
  mixins: [companyMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    AreaSelect: () => import('@/components/tools/AreaSelect'),
    ProjectInfoChange:() =>import('@/views/library/company/components/ProjectInfoChange'),
    HteLibCompanySendMessage:() =>import('@/views/library/company/modules/HteLibCompanySendMessage'),
    ApprovalInfo:() =>import('@/views/library/company/information/ApprovalInfo'),
    ProcessUserSelect: () => import('@/components/tools/projectBuildStup/ProcessUserSelect'),
  },
   provide(){
    return {parentThis :  this}
  },
  data() {
    return {
      submitUserCols:[{ label: '集团办公室', field: 'groupOfficeUser', username: '', realname: '',disabled:true, required: true},],
      
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'CompanyEditor',
      },
      options: {
        navbar:false,title:false,
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      rules: {
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        status: [{ required: true, message: '请选择', trigger: 'change' }],
        code: [{ required: true, message: '请输入', trigger: 'blur' }],
        registeredCapital: [{ required: true, message: '请输入', trigger: 'blur' }],
        legal: [{ required: true, message: '请输入', trigger: 'blur' }],
        type: [{ required: true, message: '请选择', trigger: 'change' }],
        size: [{ required: true, message: '请选择', trigger: 'change' }],
        industry: [{ required: true, message: '请选择', trigger: 'change' }],
        industryName: [{ required: true, message: '请选择', trigger: 'change' }],
        establishTime: [{ required: true, message: '请选择', trigger: 'change' }],
        approvalTime: [{ required: true, message: '请选择', trigger: 'change' }],
        businessTerm: [{ required: true, message: '请选择', trigger: 'change' }],
        companyClass: [{ required: true, message: '请选择', trigger: 'change' }],
        companyClassDetails: [{ required: true, message: '请选择', trigger: 'change' }],
        natureOfCompany: [{ required: true, message: '请选择', trigger: 'change' }],
        addressDetails: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 300, message: '详细地址不超过300字', trigger: 'blur' },
        ],
        businessScope: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 1, max: 1000, message: '经营范围不超过1000字', trigger: 'blur' },
        ],
        // companyCode: [{ required: true, message: '请输入', trigger: 'blur' }],
        //  companySalesOrganization:[{ required: true, message: '请输入', trigger: 'blur' }],
      },
      tabLoading: false,
      payColumns: [
        {
          title: '序号',
          dataIndex: 'num',
          width: '8%',
          align: 'center',
          scopedSlots: { customRender: 'num' },
        },
        {
          title: '股东',
          dataIndex: 'name',
          width: '20%',
          align: 'center',
          scopedSlots: { customRender: 'name' },
        },
        {
          title: '股权占比',
          dataIndex: 'proportion',
          width: '17%',
          align: 'center',
          scopedSlots: { customRender: 'proportion' },
        },
        {
          title: '法定代表人',
          dataIndex: 'legal',
          width: '10%',
          align: 'center',
        },
         {
          title: '成立日期',
          dataIndex: 'establishTime',
          width: '15%',
          align: 'center',
        },
         {
          title: '企业状态',
          dataIndex: 'statusName',
          width: '15%',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      sourceData: [],
      holdingColumns: [
        {
          title: '序号',
          dataIndex: 'num',
          width: '8%',
          align: 'center',
          scopedSlots: { customRender: 'num' },
        },
        {
          title: '公司名称',
          dataIndex: 'companyName',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'companyName' },
        },
        {
          title: '统一社会信用代码',
          dataIndex: 'companyCode',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'companyCode' },
        },
        {
          title: '股权占比',
          dataIndex: 'proportion',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'proportion' },
        },
         {
          title: '法定代表人',
          dataIndex: 'legal',
          width: '10%',
          align: 'center',
        },
         {
          title: '成立日期',
          dataIndex: 'establishTime',
          width: '15%',
          align: 'center',
        },
         {
          title: '企业状态',
          dataIndex: 'statusName',
          width: '15%',
          align: 'center',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '15%',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      holdingData: [],
      holdLoading: false,
      personnelList: [],
      visibleIndex: null,
      visibleModel: false,
      visibleForm: {
        userName: '',
      },
      visibleRules: {
        userName: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur',
          },
        ],
      },
      dateFormat: 'YYYY-MM-DD',
      companyId: '',
      fileList: [], // 头像
      form: {companyChangeDetail:{}}, // 基本信息
      companySizeInfo: {}, // 企业人员、知识产权
      btnLoading: false,
      enterpriseLicenseUrl: '',
      stockRightImageUrl: '',
      stockRightFile: [], // 股权穿透图 stockRightImage      
      projectBuildId:'',
      changeProjectBuildId:'',
      projectNo:'',
      saveFlag:saveFlag,
      isNewCompany:0,
      //判断新建、变更字段
      saveType:1,
      companyChanges:[],
      //变更信息
      companyChangeDetail:{},
      //公司状态
      saveStatus: null,
       companyStatus:0,
       //变更状态
       changeStatus:0,
      //变更id
      changeId:null,
      showChange:false,
      url:{
         getUserList: '/lib/hteFileClass/getUserListOnlyUpms',  
      },
      userData:[],
      userDataPolicy:[],
      fetching:false,
      currentKey:null,
    }
  },
  created() {
    
    // this.getInitData()
  },
  updated() {
    let that = this
    if (this.$refs.areaRef && this.form.addressAreaCopy) {
      this.$refs.areaRef.areaModel = this.form.addressAreaCopy
    }
    //变更信息
          
    if(this.showChange  && that.$refs.projectInfoChange){
        that.$refs.projectInfoChange.setSourceData(this.form.companyChanges || [])
        
    }
  },
  mounted() {
    this.getInitData()

  },
  computed:{
    statusText(){
      let text = ''
     let hasChange = this.hasChange
     let status =this.computedStatus
     if(hasChange){
      text = statusChangeText[status]
     }else{
        text = statusCreatText[status]
     }
     return text
    },
    statusColor(){
      let status =this.computedStatus
      return statusColor[status] || 'red'
    },
    saveBtnHasPermission(){
      //有编辑权限按钮，默认显示报工按钮，报工按钮不存在才显示
      let status = this.computedStatus
      let reportSaveBtn = this.reportSaveBtn 
      if(status == 3 && this.saveType == 1 && filterHasPermission('company:edit')){
        return true
      }else {
        return false;
      }
    },
    //报工保存按钮
    saveBtn(){
      let status = this.computedStatus
      var flagNew = (this.saveType == 1 && (!this.form.id || ( this.form.createUserId == this.userinfo.info.username) ))
      var flagChange = (this.saveType == 2 && (!this.form.companyChangeDetail.id || (this.form.companyChangeDetail.createUserId == this.userinfo.info.username) ))
     if( status == 1 && (flagNew ||flagChange)){
       return true
     }else{
       return false
     }
    },
    submitlBtn(){
      //提交审批按钮
     if(this.saveBtn && !!this.companyId ){
       return true
     }else{
       return false
     }
    },
    
    deleteBtn(){
      if(!!this.companyId && !this.hasChange && this.computedStatus == 3   && filterHasPermission('company:delete')){
           return true
      }
      return false
    },
    approvelBtn(){
    
    //有审批权限按钮
      let status = this.computedStatus

     if(status == 2 && filterHasPermission('company:approval')  ){
       return true
     }else{
       return false
     }
    },
   
    computedStatus(){
      //状态是1（创建变更）、2（审批中）、3（已入库）
     if(this.saveType == 1){

        return this.companyStatus
     }else if(this.saveType == 2){
        return this.changeStatus
     } 
    },

    hasChange(){
      if(this.saveType ==2 ){
        return true
      }else{
        return false
      }
    },
    processInstanceId(){
        if(this.hasChange){
          return this.form.companyChangeDetail.processInstanceId

        }else{
            return this.form.processInstanceId
        }
    },
    changeDisable(){
      if(this.computedStatus == 1 && !this.saveBtn){
        return true

      }else if(this.computedStatus==2 && !this.approvelBtn){
        return true
      }else if(this.computedStatus>2 ){
        return true
      }else{
         return false
      }
    },
    titleDesc(){
      let desc = '公司信息'
      if(this.form.name){
        if(this.saveType == 2){
          desc = `公司变更信息【${this.form.name}】`
          if(this.companyChangeDetail.id){
              desc = desc + `-变更编号【${this.companyChangeDetail.id}】`
          }
          
          if(this.form.companyChangeDetail && !!this.form.companyChangeDetail.projectNo){
            desc = desc + `-项目编号【${this.form.companyChangeDetail.projectNo}】` 
          }
          
        }else{
          desc = `公司信息【${this.form.name}】`
          if(!!this.form.projectNo){
          desc = desc + `-项目编号【${this.form.projectNo}】` 
          }
        }
      }
      return desc

    },
    //新建公司判断
    cpuNewCompany(){
      
      if(this.isNewCompany == 1 && this.computedStatus<3){
          return true
      }
       return false
    },
    areaLableShow(){
      //2022年12月6日前处理旧数据源
      if(this.changeDisable  && !!this.form.submitTime &&  new Date('2022-12-06').getTime()> new Date(this.form.submitTime).getTime()  ){
        return true
      }
      return false
    },
  },
  watch: {
    '$route'(to, from) {
      // 在mounted函数执行的方法，放到该处
    
      
      this.getInitData();
    },
  },
  methods: {
     fetchUser(val, type,key) {
      if (val) {
        this[key] = []
        this.fetching = true
        let params = {}
        if(type == 'init'){
          params ={nameList: val}
        }else{
          params = {name: val} 
        }
        getAction(this.url.getUserList, params).then((res) => {
          if (res.success) {
            this[key] = res.result
            this.fetching = false
          }
        })
      }
    },
    handleDictChange(value, option, targe,single=0) {      
      let arr = []
      if(single==1){
       var user =  this[option].find(item=>{
         return item.username == value
        })
        arr.push(user.realname)
      }else{
          option.forEach((item) =>
        arr.push(item.componentOptions.children[0].text ? item.componentOptions.children[0].text.trim() : '')
      ) 
      }
           
      this.$set(this.form, targe, arr.join(','))
      
    }, 
    /**
     * 获取初始信息
     */
    getDatByProject(){
      this.isNewCompany = 1
       getAction('/libraryCompany/hteLibCompany/queryByProjectBuildId', { projectBuildId: this.projectBuildId }).then((res) => {
         if (res.success) {
           
           if( !!res.result.id ){
              this.companyId = res.result.id
              this.getInitData()
           }else{
              this.saveFlag = cloneDeep(saveFlagTue)
              this.form = res.result
              this.sourceData = res.result.companyShareholders || []
              this.getLibCompanyTeam(0)
              this.$set(this.form, 'businessTermLong', '否') 
           }
            
         }
       })
      
    },
    setChangeParams(params,changeStatus=null ){
      //处理变更参数
      if(this.saveType == 2 ){
        let companyChangeDetail = {id:this.changeId, companyId:this.companyId,projectBuildId:this.projectBuildId,projectNo:this.projectNo,changeStatus:changeStatus,saveType:this.saveType}
   
        this.companyChangeDetail = Object.assign(this.companyChangeDetail,companyChangeDetail)

        params.companyChangeDetail =this.companyChangeDetail
      }
      
    },
   
    handleParams(){
      //参数处理
      const obj = this.$route.query
      this.companyId = obj.id
      this.saveType = obj.saveType || 1
      this.projectBuildId = obj.projectBuildId    
      this.projectNo = obj.projectNo
      this.changeId = obj.changeId
      if(!!this.changeId){
          this.saveType = 2
      }
      if((this.projectBuildId && this.saveType == 1) || obj.isNewCompany == 1 ) {
        this.isNewCompany = 1
      }else{
        this.isNewCompany = 0
      }
      this.setShowChange();
      let params = { id: this.companyId,companyId:this.companyId,saveType:this.saveType,projectBuildId:this.projectBuildId }
      
      this.setChangeParams(params)
      this.$forceUpdate()  
      return params
    },
    setShowChange(){
        if(this.saveType == 2 && (!!this.projectBuildId || (this.companyChangeDetail && !!this.companyChangeDetail.projectBuildId))){
        this.showChange = true

      }else{
        this.showChange = false
      }
    },
    filterHasPermission(value){
      return filterHasPermission(value)
    },
    showLoading(){
      this.btnLoading = true
    },
    getInitData() {
      let that = this
     let params = this.handleParams()
     this.initDicts()
         this.btnLoading = true
      this.tabLoading = true
      this.holdLoading = true
      postAction('/libraryCompany/hteLibCompany/queryById',params ).then((res) => {
        if (res.code == 200 && res.result) {
          let data = res.result 
          

          
          this.companyStatus = data.companyStatus || 1

          if(this.hasChange){
            that.companyChangeDetail = data.companyChangeDetail
            that.changeStatus = data.companyChangeDetail.changeStatus || 1
            that.changeId = data.companyChangeDetail.id
            this.setShowChange()
          }
          this.form = data || {}
          // 企业证照
          if (this.form.enterpriseLicense) {
            this.getImageUrl('enterpriseLicense')
          }
          // 股权穿透图
          if (this.form.stockRightImage) {
            this.getImageUrl('stockRightImage')
          }
          // 地址
          if (this.form.addressArea) {
           let addressAreaCopy =  this.form.addressArea.split('/').map((item) => {
              return item
            })
            this.$set(this.form,'addressAreaCopy',addressAreaCopy)
          }

          //企业资质
          if (this.form.qualification) {
              this.$set(this.form,'qualification', this.form.qualification.split(','))
          }else{
              this.$set(this.form, 'qualification', undefined)
          }

          // 营业期限
          this.onChangeRadio()
          
          this.companySizeInfo = data.companySizeInfo || {}

          
          data.companyTeams.forEach((item, index) => {
            if(item.typeName && item.typeName.length > 13){
              item.typeName = item.typeName.slice(0, 13) + '...'
            }            
          })
          this.personnelList = data.companyTeams || []
          data.companyShareholders = data.companyShareholders || []
          data.companyShareholders.forEach((item, index) => {
                item.key = index
              })
            this.sourceData = data.companyShareholders 
           data.prticipations = data.prticipations || []
           data.prticipations.forEach((item, index) => {
            item.key = index
          })
          this.holdingData = data.prticipations 
          if (this.form.policyAdmin ) {
            this.fetchUser(this.form.policyAdmin, 'init','userDataPolicy')
          }else{
             this.$set(this.form, 'policyAdmin', '')
          }
           if (this.form.policyCharge ) {
            this.fetchUser(this.form.policyCharge, 'init','userData')
            this.$set(this.form, 'policyCharge', this.form.policyCharge.split(","))
          }else{
             this.$set(this.form, 'policyCharge', [])
          }
        } else {
          this.$message.warning('数据加载失败:' + res.message)
        }
        
      }).catch(res=>{}).finally(res=>{
        
        this.tabLoading = false
        this.holdLoading = false
        this.btnLoading = false
      })
     
     
      // getAction('/libraryCompany/hteLibCompanySizeInfo/queryByCompanyId', { companyId: this.companyId }).then((res) => {
      //   if (res.success) {
      //      this.saveFlag.b = true
      //     this.companySizeInfo = res.result || {}
      //   }
      // })
      // this.tabLoading = true
      // this.holdLoading = true

      // getAction('/libraryCompany/hteLibCompanyShareholder/queryByCompanyId', { companyId: this.companyId }).then(
      //   (res) => {
      //     if (res.code == 200 && res.result) {
      //       this.saveFlag.c = true
      //       res.result.forEach((item, index) => {
      //         item.key = index
      //       })
      //       this.sourceData = res.result || []
      //       this.tabLoading = false
      //     } else {
      //       this.$message.warning('数据加载失败:' + res.message)
      //       this.tabLoading = false
      //     }
      //   }
      // )
      // getAction('/libraryCompany/hteLibCompanyHoldingParticipation/queryByCompanyId', {
      //   companyId: this.companyId,
      // }).then((res) => {
      //   if (res.code == 200 && res.result) {
      //     this.saveFlag.d = true
      //     res.result.forEach((item, index) => {
      //       item.key = index
      //     })
      //     this.holdingData = res.result || []
      //     this.holdLoading = false
      //   } else {
      //     this.$message.warning('数据加载失败:' + res.message)
      //     this.holdLoading = false
      //   }
      // })

      
    },
    initDicts(){
       
    },
 
    handleSaveBtnHasPermission(){
      //修改权限保存 也要走审批
      let that = this
       Modal.confirm({
          title: `${that.form.name}是否确认发起变更？`,
          onOk() {

            that.saveType = 2;
            //清空变更ID
            that.changeId = null;
            that.form.companyChangeDetail = {companyId:that.companyId}
            let params = that.getSaveparams(1)
            
              // that.save(params)     
            that.handleSave(params,1) 
            
      //  that.$refs.ruleForm.validate((valid) => {      
      //       if (valid) {
               
      //       if (!that.checkParams()) {
      //         return
      //       }
      //       that.saveType = 2;
      //       //清空变更ID
      //       that.changeId = null;
      //       that.form.companyChangeDetail = {companyId:that.companyId}
      //       let params = that.getSaveparams(1)
            
      //         // that.save(params)     
      //         that.handleSave(params,1) 
      //       } else{
      //         that.$message.warning('数据验证失败，请完善信息!' )
      //       }
      //     })

          }
        })
    },
    handleSubmit(){
      //提交审批
       codeInfoList({type:'公司库审批人员',pageSize:-1,isdel: 0,column:"code",order:"Asc"}).then((res) => {
          if (res.code == 200) {
            var records = res.result.records
            var groupOfficeUser = []
            var groupOfficeUserName = []
           groupOfficeUser = records.map(item=>{
              if(item.code == 1){
               
                return item.parentid
              }
            })
             groupOfficeUserName = records.map(item=>{
              if(item.code == 1){
              
                return item.name
              }
            })
            this.submitUserCols = [        
              { label: '集团办公室', field: 'groupOfficeUser', username: groupOfficeUser.join(','), realname: groupOfficeUserName.join(','),disabled:true, required: true},
            ]
            this.$refs.processUserSelect.doSelect();

          } else {
            this.$message.warning('操作异常:' + res.message)
          }
        })
     
    },
     selectUserConfirm(result) {
      if (!result || result.length == 0) {
        return
      }
      let data = {};
      result.forEach((item) => {
        let key = item.field;
        data[key] = item.username
      });     
      this.form.approvalPerson = data
      let params = this.getSaveparams(2)

      this.handleSave(params,2)
    },
    handleApprove(){
      //同意审批
      
      this.$refs.companyMessag.open(this.form.finishNoticeUser);
      
    },
    finishNoticeUserSubmit(data){
      //同意保存
      if(!!data.sendUsers){
        let params = this.getSaveparams(3)
        params.sendUsers = data.sendUsers
        params.comments = data.comments
        this.handleSave(params,3)
      }
    },
    handleSaveCreat(){
      //创建中、变更中状态保存
      let params = this.getSaveparams(1)
      this.handleSave(params,1)

    },
    handleSaveApprove(){
      //审批中保存
      let params = this.getSaveparams(2)
      this.handleSave(params,2)
    },
    /**
     * 保存提交
     */
    handleSave(params , status) {   
      let that = this
     
      
      let saveType = this.saveType
      if(!this.form.name || !this.form.code){
        this.$message.warning('请输入公司名称、统一社会信用代码!' )
        return
      }


      if(status == 1 ){
          that.handleSubmitPulic(params)  
      }else{
        this.$refs.ruleForm.validate((valid) => {      
            if (valid) {
            if (!this.checkParams()) {
              this.btnLoading = false
              return
            }
            that.handleSubmitPulic(params)      
          } else{
             that.$message.warning('数据验证失败，请完善信息!' )
          }
        })
      }
    },
    getSaveparams(saveStatus)  {
      this.saveStatus = saveStatus 
      let saveType = this.saveType
      let params = {...this.form,
          companySizeInfo: this.companySizeInfo,
          companyShareholders: [...this.sourceData],
          companyTeams: [...this.personnelList],
          prticipations: [...this.holdingData],
      }
        params = JSON.parse(JSON.stringify(params))
        params.saveType=this.saveType
        if(!!saveStatus) {
            if(saveType ==1 ){
            //新建查看
                params.companyStatus = saveStatus
            }else{
              //变更
              params.companyChangeDetail.changeStatus = saveStatus

            }
        }   
        
        if(this.saveType == 2 && (saveStatus==2 || saveStatus == 3) && params.companyChangeDetail.projectBuildId   ){
          //变更信息
            params.companyChanges = this.$refs.projectInfoChange.getSourceData(this.form.approvalTime);
            
          }
          return   params
        },
    handleSubmitPulic(params){
      let status = this.saveStatus
      let saveType = this.saveType
      let that = this
      
      

      if(this.saveType == 2 && (status==2 || status == 3) && that.companyChangeDetail && !!that.companyChangeDetail.projectNo){
        //变更信息
        Modal.confirm({
          title: `${that.companyChangeDetail.projectNo}变更信息的核准日期来源于基本信息的核准日期：${that.form.approvalTime}是否正确？`,
          onOk() {
            that.save(params);

          },
        })
      }else{
        that.save(params);
      }
    },
    
    save(params){
      let status = this.saveStatus
      params.qualification = !!params.qualification && params.qualification.length > 0? params.qualification.join(","):'';
      params.policyCharge = !!params.policyCharge && params.policyCharge.length > 0? params.policyCharge.join(","):'';
        this.btnLoading = true
      postAction('/libraryCompany/hteLibCompany/save', params).then((res) => {
        if (res.code == 200 && res.result) {
          let data = res.result || {}
          this.form = data
          this.companySizeInfo = data.companySizeInfo
          this.sourceData = data.companyShareholders
          this.personnelList = data.companyTeams
          this.holdingData = data.prticipations

          let query = {
            id: res.result.id,
            isNewCompany: this.isNewCompany,
            saveType: this.saveType,
          }
          if (!!data.companyChangeDetail && data.companyChangeDetail.id && this.hasChange) {
            query.changeId = data.companyChangeDetail.id
          }
          debugger;
          // if (status == 3 && this.hasChange) {
          //   //变更完成
          //   query.saveType = 1
          //   this.$router.push({ path: '/company/editor', query: { id: res.result.id } })
          // } else
          if ((this.hasChange && !this.changeId) || !this.companyId) {
            //编辑
            this.$router.push({ path: '/company/editor', query: query })
          } else {
            this.getInitData()
          }

          this.$message.success('操作成功')

        } else {
          this.$message.warning('数据提交失败:' + res.message)

        }
      }).finally(res => {
        this.btnLoading = false
      })
    },
    checkParams() {
      // const sourceValue = this.sourceData.reduce((cur, next) => {
      //   return cur + next.proportion
      // }, 0)
      // if (sourceValue > 100) {
      //   this.$message.warning('股东信息股权占比总和不能超过100')
      //   return false
      // }
      // const holdingValue = this.holdingData.reduce((cur, next) => {
      //   return cur + next.proportion
      // }, 0)
      // if (holdingValue > 100) {
      //   this.$message.warning('企业参股控股公司股权占比总和不能超过100')
      //   return false
      // }
      for (let index = 0; index <  this.sourceData.length; index++) {
        const element =  this.sourceData[index];
        if(!element.name || !element.proportion){
            this.$message.warning('请完善股东信息')
            return false
        }
      }
       for (let index = 0; index <  this.holdingData.length; index++) {
        const element =  this.holdingData[index];
        if(!element.companyName || !element.companyCode || !element.proportion){
            this.$message.warning('请完善企业参股控股信息')
            return false
        }
      }
      if(!this.form.addressAreaLabel){
        this.$message.warning('请先填写住所')
        return false
      }
      if(!this.form.registeredCapitalUnit){
         this.$message.warning('请先填写注册资金单位')
        return false
      }
      return true
    },
    /**
     * 编辑主要人员信息
     */
    handleClassOk() {
      this.$refs.ruleModelForm.validate((valid) => {
        if (valid) {
          const obj = this.personnelList[this.visibleIndex]
          obj.userName = this.visibleForm.userName
          this.$set(this.personnelList, this.visibleIndex, obj)
          this.visibleModel = false
        }
      })
    },
    handlePersonnel(index) {
      Object.assign(this.visibleForm, this.personnelList[index])
      this.visibleIndex = index
      this.visibleModel = true
    },
    handleCancel() {
      this.$refs.ruleModelForm.clearValidate()
      this.visibleModel = false
    },
    /**
     * select
     * @param: e  code值
     * @param: type  参数名
     * @param: list  字典
     */
    handleChange(e, type, list) {
      const _list = list ? list : type;
      if(type == 'industry'){
        this.form[type ] = this.dics[_list].find((item) => {
        return item.name === e
      }).code
        return
      }
      this.form[type + 'Name'] = this.dics[_list].find((item) => {
        return item.code === e || item.name === e || item.industryName === e
      }).name
    },

    handleMultipleChange(value,option){
        let arr = []
        option.forEach((item) =>
          arr.push(item.componentOptions.children[0].text ? item.componentOptions.children[0].text.trim() : '')
        )
        this.form['qualificationName'] = arr.join(",");
    },
    /**
     * 附件
     */
    fileUploadSuccess(response, type) {
      if (response && response.length) {
        this.$set(this.form, type, response[0].id)
        this.getImageUrl(type)
      }
    },
    getImageUrl(type) {
      const params = {
        busField: 'hteLibBrand',
        busType: 'picture',
        dbKey: 'Trd',
        ftpKey: 'ftp',
        id: this.form[type],
      }
      getAction('/common/getImage', params).then((res) => {
        if (res.code === 1) {
          this[type + 'Url'] = res.data
        }
      })
    },
    handleImage(event, type, targe) {
      event.preventDefault()
      event.stopPropagation()
      if (type == 'del') {
        this[targe + 'Url'] = ''
        this.$set(this.form, targe, '')
      } else {
        this.$viewerApi({
          images: [this[targe + 'Url']],
          options: this.options,
        })
      }
    },
    beforUpload(file, type) {
      /* 'image/gif', */
      const isImage = ['image/png', 'image/jpeg', 'image/jpg'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.error(`${type}只能上传png/jpeg/jpg图片文件`)
      }
      if (!isLt2M) {
        this.$message.error(`${type}图片大小不能超过 2MB`)
      }
      return isImage && isLt2M
    },
    /**
     * 新增  holdingData\ sourceData
     */
    handleAdd(type) {
      if (type == 'holdingData') {
        this[type].push({
          key: this[type].length + 1 + new Date().getTime(),
          companyName: '',
          companyCode: '',
          proportion: '',
        })
      } else {
        this[type].push({
          key: this[type].length + 1 + new Date().getTime(),
          name: '',
          proportion: '',
        })
      }
    },
     handleDelete(obj, list, index, event) {
      if (event) {
        event.preventDefault()
        event.stopPropagation()
      }
      const that = this
      Modal.confirm({
        title: '是否确认删除？',
        onOk() {
          that[list].splice(index, 1)
        },
      })
    },
    handleHolding(type , item,index,target){
      var companyName = item.companyName?item.companyName:item.name
      companyName = !!companyName ? companyName: 'ass'
       if (type=='change'){
             item.establishTime = ''
             item.legal = ''
             item.status = null
            item.statusName = ''
            item.shareholderCompanyId = null
        }
       getAction('/libraryCompany/hteLibCompany/pageList', {
        name: companyName,
      }).then((res) => {
          
          if (res.code == 200 && res.result &&  res.result.records.length == 1) {
            var company  = res.result.records[0]
            if(type=='det'){
              let path = `/company/info?id=${res.result.records[0].id}`
              let urlJump = this.$router.resolve({ path: path })
              window.open(urlJump.href, '_blank')
            }else if (type=='change'){
              item.establishTime = company.establishTime
              item.legal = company.legal
              item.status = company.status
              item.statusName = company.statusName
              item.shareholderCompanyId = company.id
            }
         
          }else{
            if(type=='det'){
              this.$message.error(`公司库不存在${item.companyName}信息`)

            }
          }
          this.$set(this[target],index,item)
      })
      
   
    },
    handleDeleteCompany() {
      
      const that = this
      Modal.confirm({
        title: '是否确认删除？',
        onOk() {
          deleteAction('/libraryCompany/hteLibCompany/delete',{id:that.companyId}).then(res=>{
              if(res.success){
                  that.$message.success( res.message)
                    that.$router.push('/company/list')
              }else{
                that.$message.warning('数据提交失败:' + res.message)
              }
            })
        },
      })
    },
    handleDeleteChangeCompany() {
      
      const that = this
      Modal.confirm({
        title: '是否确认删除？',
        onOk() {
          deleteAction('/libraryCompany/hteLibCompany/deleteChange',{id:that.changeId}).then(res=>{
              if(res.success){
                  that.$message.success( res.message)
                  window.CloseCefTab ? window.CloseCefTab():window.close()
              }else{
                that.$message.warning('数据提交失败:' + res.message)
              }
            })
        },
      })
    },
    /**
     * 住所
     */
    changeArea(event) {
      if (event && event.length ) {
        this.form.addressArea = event.join('/')
        this.form.addressAreaLabel = this.$refs.areaRef.getValueOrLabel(event.join('/'))
      }else{
        this.form.addressArea = null
        this.form.addressAreaLabel = null
        this.form.addressAreaCopy = null
      }
    },
    /**
     * 是否长期营业 
     * 否：显示营业期限
     * 是：隐藏营业期限
     */
    onChangeRadio() {
      if(this.form.businessTermLong === '是'){
        this.$set(this.form, 'businessTerm', null)
        this.$set(this.rules, 'businessTerm', [])
        this.$refs.ruleForm.clearValidate('businessTerm')
      }else{
        this.$set(this.rules, 'businessTerm', [{ required: true, message: '请选择', trigger: 'change' }])
      }
    },
    handleClick(type, item) {
      if (type === 'det') {
        let urlJump = this.$router.resolve({ path: `/company/info?id=${item}` })
        window.open(urlJump.href, '_blank')
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import './index.less';
.page-main {
  .container {
    .content {
      margin-top: 20px;
      .section-header{height: 24px;}
      .section-content {
        display: flex;
        flex-wrap: wrap;
        .info-box {
          min-width: 110px;
          height: 75px;
          border-radius: 4px;
          position: relative;
          transition: all 0.3s;
          cursor: pointer;
          border: dashed 1px #cccccc;
          text-align: center;
          padding: 10px 10px 6px 10px;
          margin-right: 16px;
          margin-bottom: 16px;
          > p {
            margin-bottom: 0;
            &:nth-child(1) {
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            &:nth-child(2) {
              height: 36px;
              margin-top: 3px;
              text-align: center;
              line-height: 17px;
              overflow: hidden;
              color: #4095e4;
            }
          }
          > span {
            position: absolute;
            right: -9px;
            top: -8px;
            color: #1890ff;
            font-size: 20px;
            background: #fff;
            line-height: 0;
          }
          > i {
            font-size: 37px;
            color: #ddd;
            margin-top: 8px;
            cursor: pointer;
          }
          &:hover {
            border: dashed 1px #1890ff;
            > i {
              color: #1890ff;
            }
          }
          &:last-child {            
            margin-right: 0;
          }
        }
      }
      .upload-demo {
        display: inline-block;
      }
      .upload-stock {
        margin-top: 10px;
        width: 100%;
        /deep/ .el-upload, /deep/ .file-upload-png{width: 100%;height: 150px}
        .file-upload-add p {
          margin-top: 5px;
        }
      }
      .upload-tip {
        vertical-align: bottom;
        margin-left: 10px;
        color: #929292;
        font-size: 13px;
        font-weight: normal;
      }
      .file-upload-png,
      .file-upload-add {
        width: 100px;
        height: 100px;
        border: 1px dashed #ddd;
        overflow: hidden;
        &.file-upload-stockadd{
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .file-upload-add {
        i {
          font-size: 37px;
          cursor: pointer;
          color: #ddd;
          margin-top: 16px;
        }
        p {
          color: #929292;
          margin-top: -15px;
        }
        &:hover {
          border-color: #1890ff;
          i,
          p {
            color: #1890ff;
          }
        }
      }
      .file-upload-png, .file-upload-stock {
        position: relative;
        img {
          width: auto;
          height: 100%;
        }
        span {
          position: absolute;
          top: 45%;
          left: 10%;
          width: 25px;
          height: 25px;
          opacity: 0;
          z-index: 1;
          line-height: initial;
          &:nth-child(1) {
            margin-top: -1px;
          }
          &:nth-child(2) {
            left: 38%;
          }
          &:nth-child(3) {
            left: 68%;
          }
          i {
            font-size: 18px;
            color: #dadada;
            vertical-align: middle;
          }
          &:hover {
            i {
              color: #fff;
            }
          }
        }
        &:before {
          position: absolute;
          z-index: 1;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          background-color: rgba(0, 0, 0, 0.6);
          opacity: 0;
          transition: all 0.3s;
          content: ' ';
        }
        &:hover {
          &:before,
          span {
            opacity: 1;
            i {
              color: #fff;
            }
          }
        }
      }
      div.file-upload-stock{
        span{top: 10px; left: auto !important;right: 10px;
          &:nth-child(2) {
            right: 80px
          }
          &:nth-child(3) {
            right: 45px
          }
        }
      }
    }
  }
  .hte-btn {
    margin-left: 10px;
  }
  .btn-box {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: center;
    z-index: 2;
  }
}
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .file-upload-model .ant-form-item-label {
  visibility: hidden !important;
}
.preview-visible {
  /deep/ .ant-modal-close-x i {
    position: relative;
    top: -12px;
    right: -12px;
  }
}
.lable-red/deep/ .ant-form-item-label label::before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
/deep/ .ant-input-number {
  width: 100%;
}
.page-main{
  .floatNav{
    background: transparent;
    border: none;
    width: 100px;
    position: fixed; top: 180px; left: 30px;z-index: 1;
    >button{display: block;margin-bottom: 10px;}
  }
}
@media (max-width: 1080px){  
  div.projectBuildStup .navigator{padding: 40px 30px 0}
  .floatNav{left: 5px;
    >button{padding: 0 2px;font-size:12px;}
  }
}
</style>
